package com.czl.module_service.view

import android.app.Dialog
import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.FragmentManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseDataBindingHolder
import com.czl.module_service.R
import com.czl.module_service.databinding.ItemTextViewBinding
import com.czl.module_service.databinding.LayoutDialogBottomSheetBinding

/**
 * @author by xubin,
 * @date on 2022/1/20.
 * PS: Not easy to write code, please indicate.
 */
class ListSheetDialogFragment(private val block: ((Int) -> Unit)) : BottomSheetDialogFragment2() {

    private lateinit var binding: LayoutDialogBottomSheetBinding

    var list: MutableList<String> = arrayListOf()

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        if (context == null) {
            return super.onCreateDialog(savedInstanceState)
        }
        val dialog = BottomSheetDialog2(requireContext())
        binding = LayoutDialogBottomSheetBinding.inflate(layoutInflater)
        dialog.setDimAmount(0.5f)
        dialog.setContentView(binding.root)
        dialog.setCornerRadius(12f, Color.WHITE)
        setupView()
        return dialog
    }

    private fun setupView() {
        binding.recyclerView.run {
            adapter = ListSheetAdapter(list).apply {
                setOnItemChildClickListener { _, _, position ->
                    this@ListSheetDialogFragment.block.invoke(position)
                    this@ListSheetDialogFragment.dismiss()
                }
            }
            addItemDecoration(DividerItemDecoration(requireContext(), 1, 0, R.color.color_21000000))
        }
        binding.btnCancel.setOnClickListener { dismiss() }
    }

    companion object {
        fun showBottomSheet(
            fragmentManager: FragmentManager,
            data: MutableList<String>,
            block: ((Int) -> Unit)
        ) {
            val sheet = ListSheetDialogFragment(block)
            sheet.run {
                list = data
                show(fragmentManager, "")
            }
        }
    }
}

class ListSheetAdapter(data: MutableList<String>) :
    BaseQuickAdapter<String, BaseDataBindingHolder<ItemTextViewBinding>>(
        R.layout.item_text_view,
        data
    ) {
    override fun convert(holder: BaseDataBindingHolder<ItemTextViewBinding>, item: String) {
        holder.dataBinding?.run {
            data = item
        }
        holder.dataBinding?.root?.setOnClickListener {
            getOnItemChildClickListener()?.onItemChildClick(this, it, holder.layoutPosition)
        }
    }
}
